import React, { useEffect, useReducer, useState } from 'react';
import TextArea from './input';
import Table from './table';
import Styles from './style.less';
import { getPrimaryTree, getSecondaryTree, getTertiaryTree } from './service';
import { devopsBatch } from './service';
import { Tree, Row, Col, message, notification } from 'antd';

interface PageProps {}

interface Tree {
  title: string;
  key: string;
  isLeaf?: boolean;
  children?: Tree[];
}

const ConfigCommands: React.FC<PageProps> = ({}) => {
  const [treePrimary, setTreePrimary] = useState<Tree[]>([]);

  const [select, setSelect] = useState<any[]>([]);

  const [data, setData] = useState<any[]>([]);

  // 请求一级菜单
  useEffect(() => {
    const treePrimary: Tree[] = [];
    (async () => {
      const primary = await getPrimaryTree();
      if (primary && primary.code == 200) {
        const data = primary.data;
        for (let i = 0; i < data.length; i++) {
          treePrimary.push({
            title: data[i],
            key: data[i],
            isLeaf: false,
            children: [],
          });
        }
      }
      setTreePrimary(treePrimary);
      return treePrimary;
    })();
  }, []);

  // 请求二级菜单
  const Secondary = (key: string, level: any[]) => {
    return new Promise<any>((resolve, reject) => {
      getSecondaryTree({ name: key as string }).then(secondary => {
        if (secondary && secondary.code == 200) {
          const treeSecondary: Tree[] = [];
          Object.entries(secondary.data.regions).forEach(i => {
            treeSecondary.push({
              title: `${i[0]} (${i[1]})`,
              key: `${i[0]}/-/${key}`,
              children: [],
            });
          });
          setTreePrimary(state => {
            state[level[1]].children = treeSecondary;
            return [...state];
          });
        }
        resolve();
      });
    });
  };

  // 请求三级 菜单
  const Tertiary = (key: string, level: any[]) => {
    let SecondaryKey = key.split('/-/')[0];
    return new Promise(async (resolve, reject) => {
      const tertiary = await getTertiaryTree({
        name: SecondaryKey as string,
        cloud: treePrimary[level[1]].key,
      });
      console.log(key, tertiary);
      setTreePrimary(state => {
        const prat = state[level[1]].children?.[level[2]];
        prat &&
          (prat.children = tertiary.data.nodes?.map(i => {
            return {
              title: i.outer,
              key: `${i.outer}/-/${key}`,
              isLeaf: true,
            };
          }));
        return [...state];
      });
      resolve();
    });
  };

  // 执行命令
  const onFinish = async (values: any) => {
    // echo 1
    select.length === 0 && message.error('请选择执行命令的目标');
    for (let i = 0; i < select.length; i++) {
      console.log(select[i]);
      const res: any = await devopsBatch({
        ...values,
        ...select[i],
      }).catch(err => console.log(err));
      console.log(res);
      setData(state => {
        return [
          ...state,
          ...Object.entries(res.data).map(i => {
            return {
              ip: i[0],
              why: i[1],
            };
          }),
        ];
      });
      if (res.code == 200) {
        notification.success({
          message: `执行成功`,
        });
      }
    }
  };

  return (
    <Row className={Styles.row}>
      <Col span={7} className={Styles.col}>
        <p>选择执行目标</p>
        <Tree
          checkable
          showLine={{
            showLeafIcon: false,
          }}
          loadData={async ({ key, children, pos }) => {
            if (children?.length) return;
            const level = pos.split('-').map(Number); // 节点路径
            switch (level.length) {
              // 获取二级
              case 2:
                return Secondary(key as string, level);
              // 获取三级
              case 3:
                return Tertiary(key as string, level);
            }
          }}
          treeData={treePrimary}
          height={800}
          onCheck={checks => {
            checks = checks as string[];
            const reg = new RegExp('(/-/)', 'g');

            // 云平台
            const platform = checks.filter(i => {
              let is = !reg.test(i as string);
              reg.lastIndex = 0;
              return is;
            });

            // 城市
            const surplus = checks.filter(i => {
              let keyPath = (i as string).split('/-/');
              return (
                !platform.includes(keyPath[keyPath.length - 1]) &&
                keyPath.length === 2
              );
            });

            // ip
            const ip = checks.filter(i => {
              let keyPath = (i as string).split('/-/');
              return (
                !platform.includes(keyPath[keyPath.length - 1]) &&
                keyPath.length === 3
              );
            });

            let concat = platform.concat(surplus) as string[];
            let city: any[] = concat.map(i => {
              switch (true) {
                case !i.match(reg):
                  // 平台
                  return {
                    cloud: i,
                  };
                case i.match(reg) && i.match(reg)?.length === 1:
                  let path = i.split('/-/');
                  let params: any = {
                    cloud: path[path.length - 1],
                    region: path[0],
                  };
                  let nodes = ip.filter(ip =>
                    (ip as string).includes(i as string),
                  );
                  nodes.length &&
                    (params.nodes = nodes.map(i => {
                      return (i as string).split('/-/')[0];
                    }));
                  // 城市
                  return params;
              }
            });
            if (city.length === 0) {
              setSelect([
                {
                  nodes: ip.map(i => {
                    return (i as string).split('/-/')[0];
                  }),
                },
              ]);
            } else {
              setSelect(city);
            }
          }}
        />
      </Col>
      <Col span={16} className={Styles.col}>
        <Row>
          <Col span={24} className={Styles.col}>
            <TextArea onFinish={onFinish} />
          </Col>
        </Row>
        <Row>
          <Col span={24} className={Styles.col}>
            <Table data={data} />
          </Col>
        </Row>
      </Col>
    </Row>
  );
};

export default ConfigCommands;
